package com.playball.lottery.frm.buyhall;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.ApplicationData;
import com.playball.lottery.R;
import com.playball.lottery.adapter.OrderAdapter;
import com.playball.lottery.bean.OrderBean;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.fragment.frm.TouZhuFragment;
import com.playball.lottery.nt.animal.AnimalServiceImpl;
import com.playball.lottery.util.DefConstants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 订单界面
 */
public class AnimalBetActivity extends Activity implements DefConstants,View.OnClickListener {

    private TextView top_title_back,top_title_bace_info;
    private TextView top_title_info;    // 标题
    private ListView listView;
    private TextView tv_submit;//确认
    private CheckBox checkbox;
    private TextView tv_zushu,tv_money;//组数，金额


    private int playTypeId = 0;
    private int lotID;
    private String issueID;
    private String issueName;
    private String strPlayType;
    private String pl = "";
    private List<String> numbers = new ArrayList<String>();
    private List<Map<String, Object>> numArr = new ArrayList<Map<String, Object>>();;
    private double totalBetMoney = 0;
    private String userID;
    private String action;
    private int buy_icon;
    private List<String> numberDispaly = new ArrayList<String>();

    public AnimalServiceImpl animalService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.danqiu_order);

        animalService=new AnimalServiceImpl();
        // userID = "NzU2";
        userID = ApplicationData.getInstance().getUserID();
        action = "207";

        //初始化控件
        initView();
        initViewChange();
    }

    public void initView(){
        top_title_back=(TextView)findViewById(R.id.top_title_back);
        top_title_back.setVisibility(View.VISIBLE);
        top_title_back.setOnClickListener(this);
        top_title_bace_info=(TextView)findViewById(R.id.top_title_bace_info);
        top_title_bace_info.setText("订单确认");
        top_title_info = (TextView)findViewById(R.id.top_title_info);
        top_title_info.setText("订单确认");

        listView=(ListView)findViewById(R.id.listview_order);
        tv_submit=(TextView)findViewById(R.id.tv_submit);//确定
        tv_submit.setOnClickListener(this);
        checkbox=(CheckBox)findViewById(R.id.checkbox);
        tv_zushu=(TextView)findViewById(R.id.tv_zushu);
        tv_money=(TextView)findViewById(R.id.tv_money);

    }

    private void initViewChange() {
        // 获得传来的数组，并放入ListView
        Intent intent = getIntent();
        issueID = intent.getStringExtra("IssueID");// 可以不要
        issueName = intent.getStringExtra("IssueName");// -1 最新的
        lotID = intent.getIntExtra("LotID", LOT_ID_ANIMAL);
        playTypeId = intent.getIntExtra("PlayTypeId", 0);
        strPlayType = intent.getStringExtra("strPlayType");
        pl = intent.getStringExtra("pl");
        numbers = getIntent().getStringArrayListExtra("numbers");
        numberDispaly = getIntent().getStringArrayListExtra("numberDispaly");
        ArrayList<OrderBean> orderBeans = new ArrayList<OrderBean>();
        totalBetMoney = 0;

        if (playTypeId == 9703 || playTypeId == 9706 || playTypeId == 9709 || playTypeId == 9710) {
            // 连码
            int numberOfBets = intent.getIntExtra("numberOfBets", 1);

            for (int i = 0; i < numbers.size(); i++ ) {
                String item = numbers.get(i);
//            System.out.println("item is " + item);
                String[] itemArray = item.split(",");

                OrderBean orderBean = new OrderBean();
                orderBean.setBetContent( pl + " " + itemArray[1]);

                orderBean.setBetMoney(String.valueOf(Double.valueOf(itemArray[2]) * numberOfBets));
                orderBean.setBetOdds(itemArray[3]);
                orderBeans.add(orderBean);

                Map<String, Object> map = new HashMap<String, Object>();

                map.put("playid", itemArray[0]);
                map.put("number", itemArray[1]);
                map.put("money", String.valueOf(Double.valueOf(itemArray[2]) * numberOfBets));

                numArr.add(map);

                totalBetMoney += Double.valueOf(itemArray[2]) * numberOfBets;
            }

            tv_zushu.setText(strPlayType + "注数：" + numberOfBets);
            tv_money.setText("" + totalBetMoney);
        } else if ( playTypeId == 9722 ) {
            // 正码
            for (int i = 0; i < numbers.size(); i++ ) {
                String item = numbers.get(i);
                String[] itemArray = item.split(",");

                OrderBean orderBean = new OrderBean();
                orderBean.setBetContent(strPlayType + " " + itemArray[1]);

                orderBean.setBetMoney(itemArray[2]);
                orderBean.setBetOdds(itemArray[3]);
                orderBeans.add(orderBean);

                Map<String, Object> map = new HashMap<String, Object>();

                map.put("playid", itemArray[0]);
                map.put("number", itemArray[1]);
                map.put("money", itemArray[2]);

                numArr.add(map);

                totalBetMoney += Double.valueOf(itemArray[2]);
            }

            int countOfRecord = numbers.size();
            tv_zushu.setText("注数：" + countOfRecord);
            tv_money.setText("" + totalBetMoney);
        } else {
            for (int i = 0; i < numbers.size(); i++ ) {
                String item = numbers.get(i);
                String tv_msg=numberDispaly.get(i);
//            System.out.println("item is " + item);
                String[] itemArray = item.split(",");

                OrderBean orderBean = new OrderBean();
                if(strPlayType.equals("两面盘" )){
                    orderBean.setBetContent(strPlayType + " " + itemArray[1]+tv_msg);
                }
                else if(strPlayType.equals("单球")){
                    orderBean.setBetContent(strPlayType + " " +tv_msg);
                }

                else{
                    orderBean.setBetContent(strPlayType + " " + itemArray[1]);
                }

                orderBean.setBetMoney(itemArray[2]);
                orderBean.setBetOdds(itemArray[3]);
                orderBeans.add(orderBean);

                Map<String, Object> map = new HashMap<String, Object>();

                map.put("playid", itemArray[0]);
                map.put("number", itemArray[1]);
                map.put("money", itemArray[2]);

                numArr.add(map);

                totalBetMoney += Double.valueOf(itemArray[2]);
            }

            int countOfRecord = numbers.size();
            tv_zushu.setText("注数：" + countOfRecord);
            tv_money.setText("" + totalBetMoney);
        }




        // 获取list集合
        // 传过来的list集合可以是实体类list    也可以是map集合
        OrderAdapter adapter=new OrderAdapter(AnimalBetActivity.this,orderBeans);
        listView.setAdapter(adapter);

        String myStr = "issueID-" + issueID + " issueName-" + issueName + " lotID-"+lotID +
                " playTypeId-"+playTypeId+" strPlayType-"+strPlayType+" pl-" + pl +
                " numbers-" + numbers;
//        System.out.println(myStr);
    }

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    Call post(String url, String json, Callback callback) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);
        return call;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //确认
            case R.id.tv_submit:
                if(checkbox.isChecked()==true){

                    String url = animalService.getURLOfBet(numArr,String.valueOf(totalBetMoney),
                            lotID,Integer.valueOf(issueID),issueName,userID,action);
                    System.out.println("url is " + url);
                    post(url, "", new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                String responseStr = response.body().string();
                                // Do what you want to do with the response.
//                                System.out.println(responseStr);
                                if (responseStr != null) {

                                }
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(responseStr);
                                    final String code = jsonObject.getString("Code");
                                    final String msg = jsonObject.getString("Data");
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (code.equals("0")) {
                                                buy_icon = R.drawable.buy_success;
                                                new ShowTipDialog().showBuyInfo(AnimalBetActivity.this, msg, "投注成功", buy_icon, "");
                                            } else {
                                                buy_icon = R.drawable.buy_failure;
                                                new ShowTipDialog().showBuyInfo(AnimalBetActivity.this, msg, "购买失败", buy_icon, "");
                                            }
                                        }
                                    });

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }else {
                                // Request not successful
                            }
                        }
                    });

                }else{
                    Toast.makeText(AnimalBetActivity.this,"请勾选同意服务条款！",Toast.LENGTH_LONG).show();
                }
                break;

            case R.id.top_title_back:
                finish();
                break;
        }
    }
}
